<script setup lang="ts">
import { reactive, watchEffect, computed, ref, shallowRef } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useSkuInfo } from '@/stores/skuInfo';
import { useProductInfo } from '@/stores/productInfo';
import type { ProductForm } from '@/types/product';
import { showConfirmDialog, showSuccessToast } from 'vant';
import { useLargenScreen } from '@/composables/useLargenScreen';
import { useCategoryList } from '../hooks/useCategoryList';
import { submitGoods, tGoodsDetail, skuDetail } from '@/common/api/hbMarket';
import { useToastLoading } from '@/composables/useToastLoading';
import imageUploader from '@/components/imageUploader.vue';
import { useUserInfo } from '@/stores/userInfo';
import passwordDialog from '../components/passwordDialog.vue';

// 监听浏览器窗口变化
useLargenScreen();

const passwordDialogRef = shallowRef<InstanceType<typeof passwordDialog>>();

const skuInfo = useSkuInfo();
const productInfo = useProductInfo();
const router = useRouter();
const route = useRoute();
const userInfo = useUserInfo();
// 获取分类列表
const { categoryOpt } = useCategoryList();

const skuList = computed(() => skuInfo.state.skuInfoList);
const myUserInfo = computed(() => userInfo.state);

const form = reactive<ProductForm>({
  pid: '',
  title: '', // 产品名称
  images: '', // 轮播图
  memo: '', // 备注
  category: '',
  paypassword: '', // 支付密码
  reason: '',
});

// 处理缓存
Object.assign(form, productInfo.state.productForm);
if (route.query?.pid) {
  form.pid = route.query.pid as string;
  document.title = '修改商品';
}
console.log('form详情: ', form);
watchEffect(() => {
  productInfo.setProductForm(form);
});

// 处理sku同步数据
const skuinfo = ref('');
watchEffect(() => {
  skuinfo.value = skuInfo.state.skuInfoList?.length
    ? JSON.stringify(skuInfo.state.skuInfoList.map((v, i) => ({ ...v, skuid: i })))
    : '';
});

const clear = () => {
  skuInfo.clearSkuInfo();
  productInfo.clearProductForm();
  Object.assign(form, productInfo.state.productForm);
};

const onSubmit = async () => {
  if (form.pid) {
    handleSubmitGoods();
  } else {
    try {
      await showConfirmDialog({
        title: '提示',
        message: `${myUserInfo.value.tips}\n积分余额:${myUserInfo.value.jifen}`,
      });
      passwordDialogRef.value?.open();
    } catch {
      /** empty */
    }
  }
};

// 发布商品
const loading = ref(false);
const handleSubmitGoods = async () => {
  loading.value = true;
  try {
    const res = await submitGoods({ ...form });
    console.log('onSubmit: ', res);
    const { pid } = res.result.data;
    if (res.status === 0) {
      if (form.pid) {
        showSuccessToast(res.message);
        router.back();
      } else {
        clear();
        if (pid) {
          router.replace(`/hbMarket/productForm?pid=${pid}`);
          form.pid = pid;
          document.title = '修改商品';
          getDetail();
          getSkuDetail();
        }
      }
    }
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};

// 支付密码弹框提交
const handlePasswordSubmit = (password: string) => {
  form.paypassword = password;
  handleSubmitGoods();
};

// 获取商品详情
const detailLoading = ref(false);
const getDetail = async () => {
  detailLoading.value = true;
  try {
    const res = await tGoodsDetail({ pid: form.pid });
    Object.assign(form, res.result.data);
    // console.log('res: ', res.result.data);
  } catch {
    /** empty */
  } finally {
    detailLoading.value = false;
  }
};

const skuDetailLoading = ref(false);
const getSkuDetail = async () => {
  skuDetailLoading.value = true;
  try {
    const res = await skuDetail({ pid: form.pid });
    skuInfo.setSkuInfoList(res.result.list);
    console.log('getSkuDetail: ', res.result.list);
  } catch {
    /** empty */
  } finally {
    skuDetailLoading.value = false;
  }
};

if (form.pid) {
  getDetail();
  getSkuDetail();
}
useToastLoading([detailLoading, skuDetailLoading]);

// 跳转规格参数
const toSku = () => {
  router.push({
    path: '/hbMarket/productSkuForm',
    query: {
      pid: form.pid,
    },
  });
};
</script>
<template>
  <div class="productForm">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.title"
          name="title"
          label="产品名称"
          placeholder="产品名称"
          :rules="[{ required: true, message: '请填写产品名称' }]"
        />
        <form-pricker
          v-model="form.category"
          ref="cardTypeRef"
          label="分类"
          name="card_info_card_type"
          :columns="categoryOpt"
        />
        <imageUploader
          label="图片"
          name="images"
          :max-count="6"
          v-model="form.images"
          :rules="[{ required: true, message: '请上传图片' }]"
        />
        <van-field
          v-if="form.pid"
          :model-value="skuinfo"
          label-align="top"
          is-link
          readonly
          name="sku"
          label="规格参数"
          placeholder="请选择规格参数"
          @click="toSku"
          :rules="[{ required: true, message: '请填写规格参数' }]"
        >
          <template #input v-if="skuList.length">
            <div class="text-[#666666]">
              <div>{{ skuList.map((v) => v.skuname).join('，') }}</div>
            </div>
          </template>
        </van-field>
        <van-field
          v-model="form.memo"
          rows="2"
          autosize
          label="描述信息"
          type="textarea"
          maxlength="100"
          placeholder="请输入描述信息"
          show-word-limit
        />
        <van-cell v-if="form.reason" title="拒绝原因" :value="form.reason" />
        <!-- <van-field name="detail" class="detail" label="商品详情">
          <template #input>
            <div class="w-full pt-2">
              <editor v-model="form.detail" />
            </div>
          </template>
        </van-field> -->
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit" color="#EC2D69" :loading="loading">
          提交
        </van-button>
      </div>
      <!-- 底部安全区 -->
      <div class="van-safe-area-bottom"></div>
    </van-form>
    <!-- 支付密码弹窗 -->
    <passwordDialog ref="passwordDialogRef" @on-submit="handlePasswordSubmit" />
  </div>
</template>
<style lang="less" scoped>
.productForm {
  min-height: 100%;
  background: #f7f8fa;
  padding: 15px 0;
  .detail {
    :deep(.van-field__value) {
      width: 100%;
    }
  }
}
</style>
